import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fsharing/core/models/bank.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/bank_delete_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/bank_list_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class BankPage extends StatelessWidget {
  final bool selectable;

  BankPage({
    Key key,
    @required this.selectable,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => BankListModel(Provider.of(context, listen: false), selectable),
        ),
        ChangeNotifierProvider(
          create: (context) => BankDeleteModel(Provider.of(context, listen: false)),
        )
      ],
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text('银行卡'),
          ),
          body: Consumer<BankListModel>(
            builder: (context, model, child) {
              switch (model.viewState) {
                case ViewState.busy:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ViewState.error:
                  return Center(
                    child: Text(model.errorMessage),
                  );
                case ViewState.success:
                  return _SuccessWidget(
                    list: model.list,
                  );
                default:
                  return Container();
              }
            },
          ),
        ),
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final List<Bank> list;

  const _SuccessWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: CustomScrollView(
        slivers: <Widget>[
          _HeaderWidget(),
          _BankListWidget(
            list: list,
          ),
          _BottomWidget(),
        ],
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  const _HeaderWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/cart/img_store.png'),
            fit: BoxFit.fill,
          ),
        ),
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(width: 12),
            Image.asset('assets/images/bank/ic_bank.png', width: 22),
            SizedBox(width: 10),
            Text('我的银行卡', style: TextStyle(fontSize: 17))
          ],
        ),
      ),
    );
  }
}

class _BankListWidget extends StatelessWidget {
  final List<Bank> list;

  const _BankListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverFixedExtentList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          return _BankItemWidget(
            bank: list[index],
          );
        },
        childCount: list.length,
      ),
      itemExtent: 50,
    );
  }
}

class _BankItemWidget extends StatelessWidget {
  final Bank bank;

  const _BankItemWidget({
    Key key,
    @required this.bank,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Slidable(
      child: GestureDetector(
        child: Container(
          alignment: Alignment.center,
          color: Colors.white,
          margin: EdgeInsets.only(bottom: 0.5),
          child: Row(
            children: <Widget>[
              SizedBox(width: 12),
              Expanded(
                child: Text(
                  bank.accountTypeName ?? '',
                  style: TextStyle(color: Color(0xFF181818), fontSize: 17),
                ),
              ),
              Text(
                bank.bankCardId ?? '',
                style: TextStyle(color: Color(0xFF181818), fontSize: 17),
              ),
              Icon(Icons.keyboard_arrow_right, color: Colors.black54),
              SizedBox(width: 12),
            ],
          ),
        ),
        onTap: () => _onItemClicked(context, bank),
      ),
      actionPane: SlidableDrawerActionPane(),
      secondaryActions: <Widget>[
        IconSlideAction(
          color: Colors.red,
          icon: Icons.delete,
          onTap: () => _onBankDelete(context),
        )
      ],
    );
  }

  void _onItemClicked(BuildContext context, Bank bank) async {
    BankListModel bankListModel = Provider.of(context, listen: false);
    if (bankListModel.selectable) {
      Navigator.of(context).pop(bank);
    } else {
      _pushBankEditPage(context, bank);
    }
  }

  void _onBankDelete(BuildContext context) async {
    BankDeleteModel bankDeleteModel = Provider.of(context, listen: false);
    ViewState viewState = await bankDeleteModel.bankDelete(bank.id);
    switch (viewState) {
      case ViewState.error:
        showToast(bankDeleteModel.errorMessage);
        break;
      default:
        BankListModel bankListModel = Provider.of(context, listen: false);
        bankListModel.refreshData();
        break;
    }
  }
}

class _BottomWidget extends StatelessWidget {
  const _BottomWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 68),
        alignment: Alignment.center,
        child: GestureDetector(
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/login/img_login.png'),
                fit: BoxFit.fill,
              ),
            ),
            width: 256,
            height: 65,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset('assets/images/bank/ic_add.png', width: 18),
                SizedBox(width: 13),
                Text(
                  '添加银行卡',
                  style: TextStyle(fontSize: 18),
                )
              ],
            ),
          ),
          onTap: () => _pushBankEditPage(context, null),
        ),
      ),
    );
  }
}

void _pushBankEditPage(BuildContext context, Bank bank) async {
  var result = await Navigator.of(context).pushNamed('/bank/edit', arguments: bank);
  if (result is bool ? result : false) {
    BankListModel bankListModel = Provider.of(context, listen: false);
    bankListModel.refreshData();
  }
}
